import { Badge, Image } from '@nutui/nutui-react';
import dayjs from 'dayjs';
import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';

import { apiWinReceiveGoodsByPost } from '@/application/apis/win';
import { ROUTE_MAP } from '@/application/constants/routerMap';
import { useGlobal } from '@/application/context/global';

import { useHome } from '../context';

export default function Btn() {
  const { setShowTask, loginCheck, taskUnFinished, reachCardInfo } = useHome();
  const { activityInfo: activity, goodInfo } = useGlobal();
  const navigate = useNavigate();
  const btnStatus = useMemo(() => {
    if (dayjs().isBefore(dayjs(activity?.startDate), 'day')) {
      return 'notStart';
    }
    if (dayjs().isAfter(dayjs(activity?.endDate), 'day')) {
      return 'finished';
    }
    if (reachCardInfo?.finished && !reachCardInfo?.received) {
      return 'receive';
    }
    if (reachCardInfo?.received) {
      return 'hasReceive';
    }
    return 'normal';
  }, [activity, reachCardInfo]);

  const btnImg = useMemo(() => {
    if (reachCardInfo?.goodStock === false) {
      return '/images/home/btn_home_stock.png';
    }
    switch (btnStatus) {
      case 'notStart':
        return '/images/home/btn_home_start.png';
      case 'finished':
        return '/images/home/btn_home_js.png';
      case 'receive':
        return '/images/home/btn_home_receive.png';
      case 'hasReceive':
        return '/images/home/btn_home_has_receive.png';
      case 'normal':
        return '/images/home/btn_home_rw.png';
    }
  }, [btnStatus, reachCardInfo?.goodStock]);
  return (
    <div
      className="absolute left-0 right-0 top-85.75 mx-auto w-fit"
      onClick={() => {
        loginCheck(() => {
          if (btnStatus === 'normal') {
            if (reachCardInfo?.goodStock === false) return;
            setShowTask(true);
          } else if (btnStatus === 'receive') {
            apiWinReceiveGoodsByPost({
              goodsId: goodInfo?.id,
              activityId: activity?.id
            }).then(() => {
              navigate(ROUTE_MAP.AWARD_LIST);
            });
          }
        });
      }}
    >
      <Image src={btnImg} className="h-19.25 w-72" />

      {taskUnFinished &&
      taskUnFinished > 0 &&
      btnStatus === 'normal' &&
      reachCardInfo?.goodStock !== false ? (
        <Badge value={taskUnFinished} className="z-2 !absolute left-2 top-1" />
      ) : null}

      {btnStatus === 'normal' && reachCardInfo?.goodStock !== false && (
        <Image
          src={new URL('/images/home/img_home_hand.png', import.meta.env.VITE_IMG_BASE_URL).href}
          className="!absolute -right-6 top-6 h-16.5 w-16.25"
        />
      )}
    </div>
  );
}
